package com.plugins.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONObject;

public class WbSearchUtils {
	
	private static final Pattern r = Pattern.compile("粉丝(\\d*)人");
	
	/**
	 * 根据关键字搜索微博用户
	 * @param keyword
	 * @throws UnsupportedEncodingException 
	 */
	public static Integer searchUserByKeyword(String keyword) throws UnsupportedEncodingException{
		StringBuffer sb = new StringBuffer("http://weibo.cn/search/user/?vt=4");
		sb.append("&keyword=").append(URLEncoder.encode(keyword, "utf-8"));
		CloseableHttpClient httpClient = HttpUtils.httpClient;
		HttpClientContext httpContext = HttpClientContext.create();
		httpContext.setCookieStore(HttpUtils.getCookie());
		HttpGet httpGet = new HttpGet(sb.toString());
		httpGet.addHeader("User-Agent", HttpUserAgent.getUserAgent());
		httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		httpGet.addHeader("Accept-Encoding", "gzip, deflate");
		RequestConfig config = RequestConfig.custom()
				//.setProxy(new HttpHost("127.0.0.1", 8888))
				.setCookieSpec(CookieSpecs.STANDARD)
				.setRedirectsEnabled(true)
				.build();
		httpGet.setConfig(config);
		try{
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				String content = EntityUtils.toString(httpResponse.getEntity());
				Document document = Jsoup.parse(content);
				String text = document.select("span.cmt").first().text();
				Integer total = Integer.valueOf(text.replace("共", "").replace("条", ""));
				return total%10 == 0 ? total/10 : total/10 + 1;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			httpGet.releaseConnection();
		}
		return null;
	}

	/**
	 * 根据关键字搜索微博用户
	 * @param keyword
	 * @param page
	 * @throws UnsupportedEncodingException 
	 */
	public static List<Map<String, Object>> searchUserByKeyword(String keyword, Integer page) throws UnsupportedEncodingException{
		StringBuffer sb = new StringBuffer("http://weibo.cn/search/user/?vt=4");
		sb.append("&keyword=").append(URLEncoder.encode(keyword, "utf-8"));
		sb.append("&page="+page);
		CloseableHttpClient httpClient = HttpUtils.httpClient;
		HttpClientContext httpContext = HttpClientContext.create();
		httpContext.setCookieStore(HttpUtils.getCookie());
		HttpGet httpGet = new HttpGet(sb.toString());
		httpGet.addHeader("User-Agent", HttpUserAgent.getUserAgent());
		httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		httpGet.addHeader("Accept-Encoding", "gzip, deflate");
		RequestConfig config = RequestConfig.custom()
				//.setProxy(new HttpHost("127.0.0.1", 8888))
				.setCookieSpec(CookieSpecs.STANDARD)
				.setRedirectsEnabled(true)
				.build();
		httpGet.setConfig(config);
		try{
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				String content = EntityUtils.toString(httpResponse.getEntity());
				Document document = Jsoup.parse(content);
				Elements tables = document.getElementsByTag("tr");
				List<Map<String, Object>> list = new ArrayList<>();
				for(int i=0; i<tables.size(); i++){
					Element element = tables.get(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("mainpage", "http://weibo.cn"+element.select("a").first().attr("href"));
					map.put("avatar", element.select("img").first().attr("src"));
					map.put("nickname", element.select("a").get(1).text());
					map.put("addUrl", "http://weibo.cn" + element.select("a").last().attr("href"));
					Matcher m = r.matcher(element.text());
					if(m.find()){
						map.put("fans", Integer.valueOf(m.group(1)));
					}
					String addUrl = (String) map.get("addUrl");
					if(addUrl.contains("attention")){
						addUrl = addUrl.substring(addUrl.indexOf("?")+1, addUrl.indexOf("&"));
						map.put("uid", addUrl.replace("uid=", ""));
					}
					list.add(map);
				}
				return list;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			httpGet.releaseConnection();
		}
		return null;
	}
	public static void main(String[] args) throws UnsupportedEncodingException {
		System.out.println(JSONObject.toJSONString(WbSearchUtils.searchUserByKeyword("新乡", 50)));
	}
}
